package com.hejia.alauda.entity;

import javax.persistence.Column;

import org.apache.commons.codec.binary.Base64;
//import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.lang3.StringUtils;

//import com.umpay.api.util.StringUtil;

/**
 * 推广
 * 
 * @author hyr
 *
 */
public class Popularize extends BaseEntity {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3625269921361003168L;

	/**
	 * 推广来源 cookie name
	 */
	public static final String COOKIE_NAME_SOURCE = "hjsource";

	/**
	 * 访问来源 cookie name
	 */
	public static final String COOKIE_NAME_REFERER = "referer";

	/**
	 * cookie 过期时间
	 */
	public static final int COOKIE_EXPIRY = 7 * 24 * 60 * 60;

	@Column
	private PopularizeCategory category; // 类别

	@Column
	private String name; // 名称

	@Column
	private String url; // 推广URL

	@Column
	private Boolean isStopPopularize; // 是否停止推广

	@Column
	private String sourceId; // 来源ID，根据类别生成，生成后不可更改。

	@Column
	private String editor;// 最新编辑者

	public PopularizeCategory getCategory() {
		return category;
	}

	public void setCategory(PopularizeCategory category) {
		this.category = category;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Boolean getIsStopPopularize() {
		if (this.isStopPopularize == null) {
			return false;
		}
		return isStopPopularize;
	}

	public void setIsStopPopularize(Boolean isStopPopularize) {
		this.isStopPopularize = isStopPopularize;
	}

	/**
	 * 获取来源ID
	 * 
	 * @return 来源ID
	 */
	public String getSourceId() {
		return sourceId;
	}

	public void setSourceId(String sourceId) {
		this.sourceId = sourceId;
	}

	/**
	 * 获取Base64编码的广告URL
	 * 
	 * @return 编码的广告URL
	 */
	private String getEncodedAdUrl() {
		if (this.url == null || this.equals("")) {
			return "";
		}
		return Base64.encodeBase64URLSafeString(org.apache.commons.codec.binary.StringUtils
				.getBytesUtf8(this.url));
	}

	/**
	 * 获取Base64编码的广告路径URL
	 * 
	 * @return Base64编码的广告路径URL
	 */
	public String getAdPathUrl() {

		if (StringUtils.isEmpty(this.getSourceId())
				|| StringUtils.isEmpty(getEncodedAdUrl())) {
			return "";
		}

		String[] ids = this.getSourceId().replace("P:", "").split("-");
		String format = "/%s/%s/%s/%s";
		return String.format(format, ids[0], ids[1], ids[2], getEncodedAdUrl());
	}

	/**
	 * 组合来源ID
	 * 
	 * @return 来源ID
	 */
	public String combineSourceId() {

		if (category == null || category.getId() == null
				|| category.getBigger() == null
				|| category.getBigger().getId() == null || this.getId() == null) {
			return "";
		}

		return String.format(PopularizeVisit.SOURCE_ID_FORMAT, this.category
				.getBigger().getId(), this.category.getId(), this.getId());
	}

	public String getEditor() {
		return editor;
	}

	public void setEditor(String editor) {
		this.editor = editor;
	}

}
